<?php
namespace App\Repos;
use App\Models\Cate;
use App\Models\Product;
use App\Models\ProductImg;
use App\Models\ProductTagRel;
use App\Models\OrderProduct;
use App\Models\ProductSpec;
use App\Models\Spec;
use App\Models\System;
use App\Models\AdminHandlerLog;
use App\Models\Cart;
use Carbon\Carbon;
use DB;
use App\Events\AdminHanderEvent;

class ProductRepo
{

    public static function create($data,$pics=[])
    {
        $rs['status'] = false;
        try {
            DB::transaction(function () use ($data,$pics) {

                $spec_names        = array_pull($data,'spec_name');
                $spec_prices       = array_pull($data,'spec_price');
                $spec_group_prices = array_pull($data,'spec_group_price');
                $data['has_spec']    = array_get($data,'has_spec')?0:1;

                $product = Product::create($data);

                if($pics) {
                    foreach ($pics as $p) {
                        $pic['product_id'] = $product->id;
                        $pic['imgurl'] = $p;
                        ProductImg::create($pic);
                    }
                }





        if($data['has_spec']) {               
            foreach ($spec_names as $k=>$name) {         
                $ps['product_id'] = $product->id;
                $ps['spec_name']  = $name;
                $ps['spec_price'] = $spec_prices[$k]*100;
           
                ProductSpec::create($ps);
            }
        }
                

            });
            $rs['status'] = true;
            return $rs;

        } catch (\Exception $e) {
            dd($e->getMessage());
            $rs['msg'] = $e->getMessage();
            return $rs;
        }
        $rs['status'] = true;
        return $rs;
    }

    public static function update($id,$data,$pics=[])
    {
        $rs['status'] = false;
        try {
            DB::transaction(function () use ($id,$data,$pics) {
                $spec_names        = array_pull($data,'spec_name');
                $spec_prices       = array_pull($data,'spec_price');
                $spec_group_prices = array_pull($data,'spec_group_price');
                $data['has_spec']    = array_get($data,'has_spec')?0:1;


                $product = Product::where(['id'=>$id])->update($data);
                Cart::where(['product_id'=>$id])->update(['price'=>$data['price']]);
                if($pics) {
                    $where['product_id'] = $id;
                    ProductImg::where($where)->delete();
                    foreach ($pics as $k => $productImg) {
                        $img['imgurl'] = $productImg;
                        $img['product_id'] = $id;
                        ProductImg::create($img);
                    }

                }


                
                


              



            });
            $rs['status'] = true;
            return $rs;

        } catch (\Exception $e) {
            $rs['msg'] = '报错文件：'.$e->getFile().'; '.$e->getLine().'行: '.$e->getMessage();
            return $rs;
        }
        $rs['status'] = true;
        return $rs;
    }


    public static function getListPages($where=[],$num=20)
    {
        $query = Product::query();
        if(array_key_exists('name', $where) ) {
            $query->where('name','like','%'.$where['name'].'%');
            unset($where['name']);
        }

        $query->with('imgs:id,product_id,imgurl');
        $query->where($where);
        $list  = $query->orderBy('price','asc')
            ->paginate($num);
        return $list;
    }

    public static  function destroy($id)
    {
        $rs['status'] = false;
        Product::destroy($id);
        $flag = ProductImg::where(['product_id'=>$id])->delete();

        if($flag) {
            $rs['status'] = true;
        }
        return $rs;


    }

    public static function getList($where,$num=10)
    {

        $data = Product::where($where)
            ->orderBy('created_at','desc')
            ->take($num)
            ->get();
        return $data;
    }



    public static function find($where)
    {
        $data = Product::where($where)
            ->first();
        return $data;
    }



    public static function imgs($product_id)
    {
        $where['product_id'] = $product_id;
        $fields = ['id','product_id','imgurl'];
        return ProductImg::where($where)
            ->pluck('imgurl')
            ->toArray();
    }


    public static function imgDel($id)
    {
        ProductImg::destroy($id);
        return true;
    }








    // 修改产品上下架状态
    public static function ChangeStatus($id,$data)
    {
        $updateData['status'] = $data['status'];
        self::update(['id'=>$id],$updateData);
        AdminHandlerLogRepo::create('Product',$id,$data);
        //dd($adminHandlerLog);
        //event(new AdminHanderEvent($adminHandlerLog));

    }

    // 根据商品id 查询商品的tags
    public static function getSpecs($id,$type_id='')
    {
        //获取spec
        $where = [];
        if($type_id) {
            $where['product_type_id'] = $type_id;
        }

        $specs = Spec::where($where)
            ->get()
            ->toArray();
        foreach ($specs as $k => $v) {
            $psWhere['product_id'] = $id;
            $psWhere['spec_id']    = $v['id'];
            $arr = ProductSpec::where($psWhere)
                ->select(['id','spec_value','spec_price','spec_thumb','spec_name','spec_price'])
                ->get()
                ->toArray();
            $specs[$k]['values'] = $arr;
        }



        return $specs;
    }

    public static function setThumb($id,$pic)
    {
        $product = Product::find($id);
        $product->thumb = $pic;
        $product->save();
        return true;
    }


    public static function getProductSpecs($product_id)
    {
        $list = ProductSpec::where(['product_id'=>$product_id])->get();
        return $list;
    }

    public static function saveSpec($data)
    {
        ProductSpec::where(['product_id'=>$data['product_id']])->delete();
        foreach ($data['spec_value'] as $k=>$v) {
            $ps['product_id'] = $data['product_id'];
            $ps['spec_id']    = $data['spec_id'][$k];
            $ps['spec_value']  = $v;
            $ps['spec_thumb'] = array_get($data['spec_thumb'],$k);
            ProductSpec::create($ps);
        }
        return true;

    }


    /**
     * 首页推荐商品
     * @return mixed
     */
    public static function recProduct()
    {
        return Product::select(['id','name','thumb','price','market_price'])->orderBy('id','desc')->take(6)->get();
    }


    /**
     * 查询最小库存
     * @param $spescIds
     * @return mixed
     */
    public static function isNormalStock($spescIds)
    {
        return ProductSpec::whereIn('id',$spescIds)->min('spec_num');
    }


    /**
     * 加入购物车
     * @param $productId
     * @param $ProductSpecsIds
     * @return mixed
     */
    public static function getProductSpecsDetails($productId,$ProductSpecsIds)
    {
        if($ProductSpecsIds){
            return Product::where('id',$productId)->with(['productSpec'=> function($query) use($ProductSpecsIds){
                $query->whereIn('id',$ProductSpecsIds);
            }])->get();
        }else{
            return Product::where('id',$productId)->with('productSpec')->get();
        }



    }


    


    public static function orderLog($product_id)
    {
        $list =DB::table('order_products as a')
            ->join('orders as b','a.order_id','=','b.id')
            ->select('b.truename','b.created_at','a.product_num')
            ->where('a.product_id',$product_id)
            ->orderBy('b.created_at','desc')
            ->paginate(10);
        // foreach($list as $k => $v) {
        //     $name = substr_replace($v->truename,'*',1);
        //     $v->truename = $name;
        // }
        return $list;    

    


    }


    public static function autoDown()
    {
        $list = Product::where('status',1)->get();
        foreach ($list as $k => $v) {
            $endtime = strtotime($v->end_at);
            if($endtime<time()) {
                $v->status = 2;
                $v->save();
            }
        }
    }


 

}
